#!/usr/bin/python
# -*- coding: utf-8 -*-;5
# File communication.py

import xmpp
import server_config
import const
import time

class Communication:
    """Communication with the xmpp Server

    This class provide a common interface. UpLayers
    can use it communicate with the xmpp server.
    Current impelementation depend on xmpppy lib.
    This class may need reimpelement for other xmp lib
    """

    def __init__( self ):
        self.config = server_config.CommunicationConfig()
        self.messageList = []

    def start( self ):
        if self.config.debug == 'debug':
            self.client = xmpp.Client( self.config.domain, self.config.port )
        else:
            self.client = xmpp.Client( self.config.domain, self.config.port, debug=[] )

        if not self.client.connect( server = ( self.config.server, self.config.port )\
                , use_srv = False ):
            return const.CANNOT_CONNECT

        if not self.client.auth( self.config.username, self.config.passwd ):
            return const.CANNOT_AUTH

        self.client.RegisterHandler( const.PRESENCE, self.__presence_handler, makefirst=1 )
        self.client.RegisterHandler( const.MESSAGE, self.__message_handler )

        self.client.sendInitPresence()
        self.client.Process(2)

        return const.SUCCESS

    def stop( self ):
        self.client.disconnect()
        return const.SUCCESS

    def receive( self ):
        self.client.Process(1)
        messages = self.messageList[:]
        self.messageList = []
        return messages

    def send( self, message ):
        if message['type'] == const.PRESENCE:
           self.__send_presence( message )
        elif message['type'] == const.MESSAGE:
            self.__send_message( message )
        elif message['type'] == const.IQ:
            self.__send_iq( message )
        else:
            pass
        
        return const.SUCCESS

    def __presence_handler( self, connect, message ):
        if message.getType() != const.PRESENCE_SUBSCRIBE:
            return

        presence_dic = { 'type' : const.PRESENCE,
                         'from' : message.getFrom().getStripped(),
                         'to' : message.getTo().getStripped() }
        
        self.messageList.append( presence_dic )
    
    def __message_handler( self, connect, message ):
        message_dic = { 'type' : const.MESSAGE,
                        'from' : message.getFrom().getStripped(), 
                        'text' : message.getBody(), 
                        'to' : message.getTo().getStripped(),
                        'message_type' : message.getType() }

        self.messageList.append( message_dic )


    def __send_presence( self, message ):
        presence = xmpp.Presence( xmpp.JID( message['to'] ), 
                                  message['type'], 
                                  xmpp.JID( message['from'] ) )
        self.client.send( presence )

    def __send_message( self, message ):
        message = xmpp.Message( xmpp.JID( message['to'] ), 
                                message['text'], 
                                typ=const.MESSAGE_CHAT )
        self.client.send( message )

    def __send_iq( self, message ):
        node = xmpp.Node( const.IQ_ITEM, 
                          { const.JID : xmpp.JID( message['to'] ), 
                            const.IQ_SUBSCRIPTION : message['active'] } )
        iq = xmpp.Iq( message['type'], message['namespace'], playload=[ node ] )
        self.client.send( iq )

def main():
    communication = Communication()
    print 'create communication'
    if const.SUCCESS != communication.start():
        print 'open failed'
    else:
        print 'open success'

    while True:
        messageList = communication.receive()
        for message in messageList:
            print message
        time.sleep( 0.03 )

    communication.stop()

if __name__ == '__main__':
    main()

# End of communication.py
